# 数据导入导出视图
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required, permission_required
from django.http import JsonResponse, HttpResponse
from django.views.decorators.http import require_http_methods
from django.contrib import messages
from django.core.paginator import Paginator
from django.utils import timezone
import json
import logging

from .import_export_service import import_export_service
from .models import Asset, AssetCategory, Department, Location, Supplier, Consumable, Warehouse

logger = logging.getLogger(__name__)


@login_required
@permission_required('assets.add_asset', raise_exception=True)
def import_export_dashboard(request):
    """导入导出仪表板"""
    
    # 获取支持的模型和格式
    supported_models = {
        'assets': '资产',
        'categories': '资产类别',
        'departments': '部门',
        'locations': '位置',
        'suppliers': '供应商',
        'consumables': '耗材',
        'warehouses': '仓库',
    }
    
    supported_formats = {
        'csv': 'CSV文件',
        'excel': 'Excel文件',
        'json': 'JSON文件',
        'xml': 'XML文件',
    }
    
    # 获取最近的导入导出记录
    recent_activities = []  # 这里可以从日志中获取最近的活动
    
    context = {
        'supported_models': supported_models,
        'supported_formats': supported_formats,
        'recent_activities': recent_activities,
    }
    
    return render(request, 'assets/import_export/dashboard.html', context)


@login_required
@permission_required('assets.add_asset', raise_exception=True)
def import_data_view(request):
    """数据导入页面"""
    
    if request.method == 'POST':
        return handle_import_request(request)
    
    # GET请求显示导入页面
    supported_models = {
        'assets': '资产',
        'categories': '资产类别',
        'departments': '部门',
        'locations': '位置',
        'suppliers': '供应商',
        'consumables': '耗材',
        'warehouses': '仓库',
    }
    
    context = {
        'supported_models': supported_models,
    }
    
    return render(request, 'assets/import_export/import_data.html', context)


def handle_import_request(request):
    """处理导入请求"""
    try:
        # 获取参数
        model_name = request.POST.get('model_name')
        format_type = request.POST.get('format_type')
        uploaded_file = request.FILES.get('file')
        
        # 导入选项
        options = {
            'update_mode': request.POST.get('update_mode', 'create_only'),
            'ignore_errors': request.POST.get('ignore_errors') == 'on',
            'batch_size': int(request.POST.get('batch_size', 100)),
        }
        
        if request.POST.get('unique_fields'):
            options['unique_fields'] = request.POST.get('unique_fields').split(',')
        
        # 验证参数
        if not all([model_name, format_type, uploaded_file]):
            messages.error(request, '请填写所有必要参数并选择文件')
            return redirect('assets:import_data_view')
        
        # 执行导入
        result = import_export_service.import_data(
            file=uploaded_file,
            model_name=model_name,
            format_type=format_type,
            user=request.user,
            options=options
        )
        
        if result['success']:
            messages.success(request, result['message'])
            
            # 如果有错误但设置了忽略错误，显示警告
            if result.get('error_count', 0) > 0:
                messages.warning(request, f"导入过程中有 {result['error_count']} 条记录出现错误")
        else:
            messages.error(request, result['error'])
            
            # 如果有详细错误信息，存储到session中供查看
            if 'errors' in result:
                request.session['import_errors'] = result['errors']
        
        return redirect('assets:import_data_view')
        
    except Exception as e:
        logger.error(f"处理导入请求失败: {e}")
        messages.error(request, f'导入失败: {str(e)}')
        return redirect('assets:import_data_view')


@login_required
def export_data_view(request):
    """数据导出页面"""
    
    supported_models = {
        'assets': '资产',
        'categories': '资产类别',
        'departments': '部门',
        'locations': '位置',
        'suppliers': '供应商',
        'consumables': '耗材',
        'warehouses': '仓库',
    }
    
    context = {
        'supported_models': supported_models,
    }
    
    return render(request, 'assets/import_export/export_data.html', context)


@login_required
@require_http_methods(["POST"])
def export_data_api(request):
    """数据导出API"""
    try:
        data = json.loads(request.body)
        
        model_name = data.get('model_name')
        format_type = data.get('format_type')
        filters = data.get('filters', {})
        fields = data.get('fields')
        
        # 验证参数
        if not all([model_name, format_type]):
            return JsonResponse({
                'success': False,
                'error': '缺少必要参数'
            }, status=400)
        
        # 执行导出
        result = import_export_service.export_data(
            model_name=model_name,
            format_type=format_type,
            filters=filters,
            fields=fields
        )
        
        if result['success']:
            # 返回文件下载响应
            response = HttpResponse(
                result['content'],
                content_type=result['content_type']
            )
            response['Content-Disposition'] = f'attachment; filename="{result["filename"]}"'
            return response
        else:
            return JsonResponse(result, status=500)
            
    except Exception as e:
        logger.error(f"数据导出失败: {e}")
        return JsonResponse({
            'success': False,
            'error': f'导出失败: {str(e)}'
        }, status=500)


@login_required
@require_http_methods(["GET"])
def get_model_fields_api(request, model_name):
    """获取模型字段API"""
    try:
        field_config = import_export_service._get_model_field_config(model_name)
        
        if not field_config:
            return JsonResponse({
                'success': False,
                'error': '不支持的模型'
            }, status=400)
        
        # 转换为前端友好的格式
        fields = []
        for field_name, field_info in field_config.items():
            fields.append({
                'name': field_name,
                'label': field_info.get('alias', field_name),
                'type': field_info.get('type', 'str'),
                'required': field_info.get('required', False),
                'unique': field_info.get('unique', False),
            })
        
        return JsonResponse({
            'success': True,
            'fields': fields
        })
        
    except Exception as e:
        logger.error(f"获取模型字段失败: {e}")
        return JsonResponse({
            'success': False,
            'error': str(e)
        }, status=500)


@login_required
@require_http_methods(["POST"])
def validate_import_data(request):
    """验证导入数据"""
    try:
        model_name = request.POST.get('model_name')
        format_type = request.POST.get('format_type')
        uploaded_file = request.FILES.get('file')
        
        if not all([model_name, format_type, uploaded_file]):
            return JsonResponse({
                'success': False,
                'error': '缺少必要参数'
            }, status=400)
        
        # 解析文件
        data = import_export_service._parse_file(uploaded_file, format_type)
        
        # 验证数据
        validation_result = import_export_service._validate_and_clean_data(
            data, model_name, {}
        )
        
        return JsonResponse({
            'success': True,
            'validation_result': validation_result,
            'preview_data': data[:5] if data else []  # 预览前5条数据
        })
        
    except Exception as e:
        logger.error(f"验证导入数据失败: {e}")
        return JsonResponse({
            'success': False,
            'error': f'验证失败: {str(e)}'
        }, status=500)


@login_required
def download_template(request, model_name, format_type):
    """下载导入模板"""
    try:
        # 获取字段配置
        field_config = import_export_service._get_model_field_config(model_name)
        
        if not field_config:
            messages.error(request, '不支持的模型')
            return redirect('assets:import_data_view')
        
        # 生成模板数据
        template_data = []
        headers = {}
        
        for field_name, field_info in field_config.items():
            headers[field_name] = field_info.get('alias', field_name)
        
        # 添加一行示例数据
        example_data = {}
        for field_name, field_info in field_config.items():
            field_type = field_info.get('type', 'str')
            
            if field_type == 'str':
                example_data[field_name] = f'示例{field_info.get("alias", field_name)}'
            elif field_type == 'int':
                example_data[field_name] = 1
            elif field_type == 'float':
                example_data[field_name] = 1.0
            elif field_type == 'bool':
                example_data[field_name] = True
            elif field_type == 'date':
                example_data[field_name] = '2024-01-01'
            elif field_type == 'datetime':
                example_data[field_name] = '2024-01-01 12:00:00'
            else:
                example_data[field_name] = '示例值'
        
        template_data.append(example_data)
        
        # 生成文件
        result = import_export_service._generate_file_content(template_data, format_type)
        
        # 返回文件下载响应
        response = HttpResponse(
            result,
            content_type=import_export_service._get_content_type(format_type)
        )
        
        filename = f'{model_name}_import_template.{format_type}'
        response['Content-Disposition'] = f'attachment; filename="{filename}"'
        
        return response
        
    except Exception as e:
        logger.error(f"下载模板失败: {e}")
        messages.error(request, f'下载模板失败: {str(e)}')
        return redirect('assets:import_data_view')


@login_required
def view_import_errors(request):
    """查看导入错误"""
    errors = request.session.get('import_errors', [])
    
    # 分页
    paginator = Paginator(errors, 20)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)
    
    context = {
        'page_obj': page_obj,
    }
    
    return render(request, 'assets/import_export/import_errors.html', context)


@login_required
def clear_import_errors(request):
    """清除导入错误"""
    if 'import_errors' in request.session:
        del request.session['import_errors']
    
    messages.success(request, '已清除导入错误记录')
    return redirect('assets:import_data_view')


# 批量操作相关视图
@login_required
@permission_required('assets.change_asset', raise_exception=True)
def batch_operations(request):
    """批量操作页面"""
    
    operations = [
        {'key': 'update_status', 'label': '批量更新状态'},
        {'key': 'update_department', 'label': '批量更新部门'},
        {'key': 'update_location', 'label': '批量更新位置'},
        {'key': 'delete', 'label': '批量删除'},
    ]
    
    context = {
        'operations': operations,
        'departments': Department.objects.all(),
        'locations': Location.objects.all(),
    }
    
    return render(request, 'assets/import_export/batch_operations.html', context)


@login_required
@permission_required('assets.change_asset', raise_exception=True)
@require_http_methods(["POST"])
def execute_batch_operation(request):
    """执行批量操作"""
    try:
        data = json.loads(request.body)
        
        operation = data.get('operation')
        asset_ids = data.get('asset_ids', [])
        parameters = data.get('parameters', {})
        
        if not operation or not asset_ids:
            return JsonResponse({
                'success': False,
                'error': '缺少必要参数'
            }, status=400)
        
        # 获取资产查询集
        assets = Asset.objects.filter(id__in=asset_ids)
        
        if not assets.exists():
            return JsonResponse({
                'success': False,
                'error': '未找到指定的资产'
            }, status=400)
        
        # 执行批量操作
        result = execute_batch_operation_logic(operation, assets, parameters, request.user)
        
        return JsonResponse(result)
        
    except Exception as e:
        logger.error(f"执行批量操作失败: {e}")
        return JsonResponse({
            'success': False,
            'error': f'操作失败: {str(e)}'
        }, status=500)


def execute_batch_operation_logic(operation, assets, parameters, user):
    """执行批量操作逻辑"""
    
    success_count = 0
    error_count = 0
    errors = []
    
    try:
        if operation == 'update_status':
            new_status = parameters.get('status')
            if not new_status:
                return {'success': False, 'error': '缺少状态参数'}
            
            success_count = assets.update(status=new_status)
            
        elif operation == 'update_department':
            department_id = parameters.get('department_id')
            if not department_id:
                return {'success': False, 'error': '缺少部门参数'}
            
            try:
                department = Department.objects.get(id=department_id)
                success_count = assets.update(department=department)
            except Department.DoesNotExist:
                return {'success': False, 'error': '部门不存在'}
            
        elif operation == 'update_location':
            location_id = parameters.get('location_id')
            if not location_id:
                return {'success': False, 'error': '缺少位置参数'}
            
            try:
                location = Location.objects.get(id=location_id)
                success_count = assets.update(location=location)
            except Location.DoesNotExist:
                return {'success': False, 'error': '位置不存在'}
            
        elif operation == 'delete':
            # 删除操作需要逐个处理，以便记录错误
            for asset in assets:
                try:
                    asset.delete()
                    success_count += 1
                except Exception as e:
                    error_count += 1
                    errors.append({
                        'asset_id': asset.id,
                        'asset_name': asset.name,
                        'error': str(e)
                    })
        else:
            return {'success': False, 'error': '不支持的操作类型'}
        
        # 记录操作日志
        from .models_system import SystemLog
        SystemLog.objects.create(
            level='INFO',
            message=f'批量操作: {operation}',
            details={
                'user': user.username,
                'operation': operation,
                'success_count': success_count,
                'error_count': error_count,
                'parameters': parameters
            }
        )
        
        return {
            'success': True,
            'success_count': success_count,
            'error_count': error_count,
            'errors': errors,
            'message': f'操作完成: 成功 {success_count} 个，失败 {error_count} 个'
        }
        
    except Exception as e:
        logger.error(f"批量操作执行失败: {e}")
        return {
            'success': False,
            'error': f'操作失败: {str(e)}'
        }